import csv
from bs4 import BeautifulSoup

# 从文件读取 HTML 片段
def read_html_from_file(file_path):
    with open(file_path, 'r', encoding='utf-8') as file:
        return file.read()

# 将解析结果写入 CSV
def write_to_csv(data, output_file):
    with open(output_file, 'w', encoding='utf-8', newline='') as file:
        writer = csv.writer(file)
        writer.writerow(["Formula ID", "英文名", "中文名", "拼音", "来源"])  # 写入表头
        writer.writerows(data)  # 写入数据行

# 读取 HTML 片段
html_content = read_html_from_file('TCM-ID-output.html')

# 使用 BeautifulSoup 解析 HTML
soup = BeautifulSoup(html_content, "lxml")  # 你也可以使用 "html.parser"

# 提取所有 <tr> 行
rows = soup.find_all("tr")

# 存储数据
data = []

# 遍历每一行，提取数据
for row in rows:
    columns = row.find_all("td")  # 获取每行所有 <td>
    
    # 确保每行有足够的列
    if len(columns) >= 5:
        link = columns[0].find("a")["href"]
        formula = link.split("=")[-1]  # 解析 TCMF1、TCMF2...
        
        english_name = columns[1].text.strip()
        chinese_name = columns[2].text.strip()
        pinyin_name = columns[3].text.strip()
        source = columns[4].text.strip()

        # 添加到数据列表
        data.append([formula, english_name, chinese_name, pinyin_name, source])

# 输出数据到 CSV 文件
write_to_csv(data, 'output.csv')
print("数据已保存到 output.csv")

""" read_html_from_file('TCM-ID-output.html')
write_to_csv(data, 'TCM-ID-output.csv') """